<template>
  <el-select v-model="sval" clearable filterable :placeholder="placeholder||'请选择'" :style="{width}" class="small-el-input__inner" popper-class="samll-el-select-dropdown__list" :multiple="multiple" @change="onChcange">
    <el-option v-for="dt in lists" :key="dt.id" :value="dt.id" :label="dt.nick" />
  </el-select>
</template>
<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import { getUserList } from '@/api/system'
import { useUserStore } from '@/pinia/modules/user'

const userStore = useUserStore()

const props = defineProps({
  modelValue: '',
  lovCode: '',
  param2: '',
  width: {
    type: String,
    default: '100%'
  },
  params: { // 查询条件
    type: Object,
    default: {}
  },
  multiple: { // 多选
    type: Boolean,
    default: false
  },
  optLists: '',
  placeholder: '',
  keyName: '' // 返回的属性名对应的值
})
const emit = defineEmits(['update:modelValue', 'change'])
const sval = ref('')
const lists = ref('')

onMounted(() => {
  if (props.optLists) {
    lists.value = props.optLists
    sval.value = props.modelValue || '' // 设置默认选项
  } else {
    getTableData()
  }
})

watch(() => props.modelValue, (n, o) => {
  sval.value = n
})

const getTableData = async() => {
  const res = await getUserList({
    page: 1,
    limit: 1000000,
    farmId: userStore.userInfo.farmId,
    companyId: userStore.userInfo.companyId
  })
  if (res.code === 0) {
    lists.value = res.data
    // console.log("GGGGG:",props)
    sval.value = props.modelValue || '' // 设置默认选项
  }
}

const onChcange = () => {
  if (props.keyName) {
    const item = lists.value.find(ele => ele.id == sval.value)
    emit('update:modelValue', item[props.keyName])
  } else {
    emit('update:modelValue', sval.value)
  }
  if (props.multiple) { // 多选
    const slObjArr = [] // 选择的对象数据
    sval.value.forEach(item => {
      const uit = lists.value.find(ele => ele.id == item)
      slObjArr.push(uit)
    })
    emit('change', slObjArr)
  } else { // 单选
    emit('change', lists.value.find(ele => ele.id == sval.value))
  }
}

</script>

<style scoped lang="scss">
</style>
